/**
 * Created by cuppi on 2017/7/18.
 */

// import Qiniu from 'qiniu-js'
// import plupload from 'plupload/js/plupload.full.min'

let instance = null;
class QiNiuManager{
  constructor (){
    if (!instance){
      instance = this;
      global.uploadBase64Callback = this.uploadBase64Callback.bind(this);
      this.uploadImagePromiseCallback = null;
    }
    return instance;
  }

  static defaultManager(){
    return new QiNiuManager();
  }

  uploadBase64Callback(result){
    if (this.uploadImagePromiseCallback){
      if (result){
        let resultObj = JSON.parse(result);
        let imageUrl = 'http://ojljqad2c.qnssl.com/' + resultObj.key;
        if (!resultObj.key){
          window.alert('异常数据: \nresult is :' + result);
        }
        this.uploadImagePromiseCallback.resolve(imageUrl);
      } else {
        this.uploadImagePromiseCallback.reject();
      }
      this.uploadImagePromiseCallback = null;
    }
  }

  uploadImage(accessToken, key, base64){
    return new Promise((resolve, reject) => {
      this.uploadImagePromiseCallback = {resolve, reject};
      if (global.uploadImageToQiNiu){
        global.uploadImageToQiNiu(accessToken, key, base64);
      }
    })
  }
}

export default QiNiuManager;
